import React, { useCallback, useState } from "react";
import "./index.scss";

interface IProps {
  totalPages: number;
  currentPage: number;
  onPageSelected: (page: number) => void;
}

const elipsis = "  ...  ";

const StoPaginator: React.FC<IProps> = ({
  totalPages,
  currentPage,
  onPageSelected,
}) => {
  const [current, setCurrent] = useState(currentPage);

  const onPagerClick = useCallback(
    (i: number) => {
      // console.log(i, onPageSelected);
      setCurrent(i);
      onPageSelected(i);
    },
    [current]
  );

  const rederPagers = useCallback(
    (current: number) => {
      /* 
    [1,5],[],[16,20]
    [1,2][][10,14],[],[19,20]
    */
      const _render = (arrs: number[][]): React.ReactNode[] => {
        const pagers: React.ReactNode[] = [];

        arrs.map((arr) => {
          const [start, end] = arr;

          if (start && end) {
            for (let i = start; i <= end; i++) {
              pagers.push(
                <li
                  className={(i === current ? "current" : "") + " no-select"}
                  onClick={() => {
                    onPagerClick(i);
                  }}
                >
                  {i}
                </li>
              );
            }
          } else {
            pagers.push(elipsis);
          }
        });

        return pagers;
      };

      if (totalPages <= 10) {
        return _render([[1, totalPages]]);
      }

      if (current > 5 && current < totalPages - 4) {
        return _render([
          [1, 2],
          [],
          [current - 2, current + 2],
          [],
          [totalPages - 1, totalPages],
        ]);
      } else {
        return _render([[1, 5], [], [totalPages - 4, totalPages]]);
      }
    },
    [current, totalPages]
  );

  return (
    <div className="wrapper">
      <ul>
        <li className="no-select" onClick={() => onPagerClick(1)}>
          首页
        </li>
        <li
          className="no-select"
          onClick={() => {
            console.log(current, "上页");
            if (current >= 2) {
              onPagerClick(current - 1);
            }
          }}
        >
          上页
        </li>

        {rederPagers(current)}

        <li
          className="no-select"
          onClick={() => {
            if (current <= totalPages - 1) {
              onPagerClick(current + 1);
            }
          }}
        >
          下页
        </li>
        <li className="no-select" onClick={() => onPagerClick(totalPages)}>
          末页
        </li>
      </ul>
    </div>
  );
};

export default StoPaginator;
